import { defineStore } from 'pinia'
import { ref } from 'vue'
import { RouteLocationNormalized } from 'vue-router'

export interface TabItem {
  path: string
  title: string
  name: string
  meta?: any
}

export const useTabs = defineStore('tabs', () => {
  const activeTab = ref<string>('')
  const tabList = ref<TabItem[]>([])

  const addTab = (route: RouteLocationNormalized) => {
    try {
      const { fullPath, meta, name, query } = route
      let path = decodeURIComponent(fullPath)
      let title = (meta?.title as string) || (name as string) || path
      if (query?.title) {
        title = decodeURIComponent(query.title as string)
      }
      const existingTab = tabList.value.find((tab) => tab.path === path)

      if (
        !existingTab &&
        path !== '/login' &&
        path !== '/register' &&
        path !== '/' &&
        path !== '/404' &&
        path !== '/403' &&
        path !== '/500'
      ) {
        tabList.value.push({ path, title, name: name as string, meta })
      }

      if (path !== '/login' && path !== '/register') {
        activeTab.value = path
      }
    } catch (error) {
      console.error('addTab error:', error)
    }
  }

  const closeTab = (path: string) => {
    try {
      const index = tabList.value.findIndex((tab) => tab.path === path)
      if (index !== -1) {
        tabList.value.splice(index, 1)
        if (activeTab.value === path) {
          if (tabList.value.length > 0) {
            const newIndex = index > 0 ? index - 1 : 0
            activeTab.value = tabList.value[newIndex].path
          } else {
            activeTab.value = localStorage.getItem('firstPath') || '/'
          }
        }
      }
    } catch (error) {
      console.error('closeTab error:', error)
    }
  }

  const closeOtherTabs = (path: string) => {
    try {
      const currentTab = tabList.value.find((tab) => tab.path === path)
      if (currentTab) {
        tabList.value = [currentTab]
        activeTab.value = path
      }
    } catch (error) {
      console.error('closeOtherTabs error:', error)
    }
  }

  const closeAllTabs = () => {
    try {
      tabList.value = []
      activeTab.value = localStorage.getItem('firstPath') || '/'
    } catch (error) {
      console.error('closeAllTabs error:', error)
    }
  }

  return {
    activeTab,
    tabList,
    addTab,
    closeTab,
    closeOtherTabs,
    closeAllTabs,
  }
})
